<template>
  <n-modal v-model:show="dialogFormVisible" @updateShow="showChange">
    <div class="recharge-dia">
      <div class="header">
        <div class="user">
          <div class="title">牛牛币快速充值</div>
          <div class="desc">
            {{ userInfo.name }}（余额：{{ userInfo.balance }}牛牛币）
          </div>
        </div>
        <div class="close-icon" @click="close()">
          <i class="esayIcon esayIcon-guanbi1"></i>
        </div>
      </div>
      <div class="con">
        <div class="package flex">
          <div
            class="package-card"
            :class="{
              'package-card-active': item.id === queryForm.rechargeSettingId
            }"
            v-for="item in rechargeList"
            :key="item.id"
            @click="handCheck(item)"
          >
            <div class="youhui" v-if="item.discountsMoney">
              <img src="@/assets/icon/youhui.png" alt="" />
              <span>立减{{ item.discountsMoney }}元</span>
            </div>
            <div class="title">
              <span>{{ item.rechargeGold }}牛牛币</span>
            </div>
            <div class="price">
              <span>￥</span>
              <span>{{ item.rechargeMoney }}</span>
            </div>
          </div>
        </div>
        <div class="type-row">
          <div class="pay-type">
            <div class="card">
              <div class="icon">
                <QrcodeVue
                  v-if="queryForm.wxScanCode"
                  :value="queryForm.wxScanCode"
                  :size="qrCodeSize"
                ></QrcodeVue>
              </div>
              <div class="names">
                <img src="@/assets/icon/pay/weixin.png" alt="" />
                <span>扫码支付</span>
              </div>
            </div>
            <div class="card">
              <div class="icon">
                <QrcodeVue
                  v-if="queryForm.zfScanCode"
                  :value="queryForm.zfScanCode"
                  :size="qrCodeSize"
                ></QrcodeVue>
              </div>
              <div class="names">
                <img src="@/assets/icon/pay/zhifubao.png" alt="" />
                <span>扫码支付</span>
              </div>
            </div>
          </div>
          <div class="price-info">
            <div class="flex" style="align-items: flex-end">
              <div class="price">
                <span>￥</span>
                <span>{{ payPrice }}</span>
              </div>
              <div class="old-price" v-if="price !== payPrice">
                ￥{{ price }}
              </div>
            </div>
            <n-select
              class="select"
              clearable
              v-model:value="queryForm.couponId"
              :options="options"
            >
              <template #empty>
                <div>
                  <span>暂无可使用优惠券</span>
                </div>
              </template>
            </n-select>
            <div class="tips">
              <span>支付即代表你同意</span>
              <span @click="handOpen">《网站用户充值协议》</span>
            </div>
          </div>
        </div>
      </div>
      <IllusDia ref="lusRef" />
    </div>
  </n-modal>
</template>
<script setup lang="ts">
import { NModal, NSelect } from 'naive-ui'
import { computed, defineAsyncComponent, ref } from 'vue'
import { useAppsStore } from '@/stores/modules/app'
import { storeToRefs } from 'pinia'
import QrcodeVue from 'qrcode.vue'
import { useWindowSize } from '@vueuse/core/index'

const useStore = useAppsStore()
const { getUserInfo: userInfo } = storeToRefs(useStore)
const IllusDia = defineAsyncComponent(() => import('@/components/IllusDia.vue'))

interface queryFormState {
  rechargeSettingId: string | number
  couponId: null | number
  wxScanCode: string
  zfScanCode: string
}

const { width } = useWindowSize()
const qrCodeSize = computed(() => {
  const bili = width.value / 1920
  return Number((100 * bili).toFixed(2))
})
const queryForm = ref<queryFormState>({
  rechargeSettingId: '',
  couponId: null,
  wxScanCode: '',
  zfScanCode: ''
})
const lusRef = ref()
const handOpen = () => {
  lusRef.value.open('RECHARGE_AGREEMENT')
}
const options = ref()

const price = computed(() => {
  if (queryForm.value.rechargeSettingId) {
    const info = rechargeList.value.find(
      (item: any) => item.id === queryForm.value.rechargeSettingId
    )
    if (info) {
      return info.rechargeMoney
    }
  }
  return 0
})
const payPrice = computed(() => {
  if (queryForm.value.couponId) {
    const info = options.value.find(
      (el: any) => el.value === queryForm.value.couponId
    )
    if (info) {
      const total = Number((price.value - info.money).toFixed(2))
      return total >= 0 ? total : 0
    }
  }
  return price.value
})
let timer: any = null
const handPay = async () => {
  msgUtil.$message.warning('开发中...')
  // const { data } = await systemApi.rechargePay({
  //   rechargeSettingId: queryForm.value.rechargeSettingId,
  //   couponId: queryForm.value.couponId
  // })
  // queryForm.value.wxScanCode = data.wxScanCode
  // queryForm.value.zfScanCode = data.zfScanCode
  // clearTimer()
  // timer = setTimeout(() => {
  //   payResult(data.id)
  // }, 3000)
}
// const payResult = async (id: string | number) => {
//   const { data } = await systemApi.recharOrderDetail(id)
//   if (data.orderStatus === 'PAID') {
//     toast.success('支付成功')
//     doUserInfo()
//     close()
//     return
//   }
//   clearTimer()
//   timer = setTimeout(() => {
//     payResult(id)
//   }, 3000)
// }
const clearTimer = () => {
  if (timer) {
    clearTimeout(timer)
    timer = null
  }
}

const handCheck = (e: any) => {
  if (queryForm.value.rechargeSettingId === e.id) return
  queryForm.value.rechargeSettingId = e.id
  getCouList()
}

const dialogFormVisible = ref(false)
const showChange = (e: boolean) => {
  if (!e) {
    close()
  }
}
const close = () => {
  clearTimer()
  dialogFormVisible.value = false
}
const rechargeList: any = ref([])
const open = async (couInfo?: any) => {
  // const { data } = await systemApi.rechargeList()
  const data = []
  rechargeList.value = data
  if (couInfo && couInfo.isReduction) {
    const starInfo = data.find(
      (el: any) => el.rechargeMoney >= couInfo.satisfyMoney
    )
    queryForm.value.rechargeSettingId = starInfo.id
  } else {
    queryForm.value.rechargeSettingId = data[0].id
  }
  getCouList(couInfo ? couInfo.id : null)
  dialogFormVisible.value = true
}

const getCouList = async (id?: null | number) => {
  // const { data } = await systemApi.recharCouList({
  //   money: price.value
  // })
  const data = []
  if (data && data.canCoupons) {
    options.value = data.canCoupons.map((el: any) => {
      return {
        label: el.isReduction
          ? `满${el.satisfyMoney}减${el.money}`
          : `${el.money}元无门槛现金券`,
        value: el.id,
        money: el.money
      }
    })
  }
  if (id) {
    queryForm.value.couponId = id
  } else if (queryForm.value.couponId) {
    const isSome = options.value.some(
      (el: any) => el.value === queryForm.value.couponId
    )
    if (!isSome) {
      queryForm.value.couponId = null
    }
  }
  handPay()
}
defineExpose({
  open
})
</script>

<style scoped lang="scss">
.recharge-dia {
  width: 712px;

  .header {
    height: 120px;
    padding: 0 24px 20px 24px;
    border-radius: 20px 20px 0 0;
    background: linear-gradient(270deg, #ffa422 0%, #f24f46 100%);
    display: flex;
    align-items: center;
    justify-content: space-between;

    .user {
      .title {
        font-size: 24px;
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        color: #ffffff;
      }

      .desc {
        margin-top: 5px;
        font-size: 14px;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #ffffff;
      }
    }

    .close-icon {
      cursor: pointer;
      width: 16px;
      height: 16px;
      display: flex;
      align-items: center;
      justify-content: center;

      i {
        font-size: 24px;
        color: #fff;
      }

      &:hover {
        i {
          color: orangered;
        }
      }
    }
  }

  .con {
    min-height: 400px;
    margin-top: -25px;
    background: #fff;
    border-radius: 20px;
    box-sizing: border-box;
    padding: 34px;

    .package {
      gap: 20px 24px;

      .package-card {
        width: 158px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #dddddd;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        padding-bottom: 25px;
        cursor: pointer;
        position: relative;

        .youhui {
          position: absolute;
          left: -1px;
          top: -12px;
          display: flex;
          align-items: center;
          padding: 4px 11px;
          background: linear-gradient(270deg, #fe8d65 0%, #fe4d21 100%);
          border-radius: 9px 0px 9px 0px;

          img {
            width: 11px;
            height: 11px;
            display: block;
          }

          span {
            margin-left: 5px;
            font-size: 14px;
            font-family: PingFang SC, PingFang SC;
            font-weight: 400;
            color: #ffffff;
          }
        }

        .title {
          padding-top: 40px;
          font-size: 14px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          color: #333333;
        }

        .price {
          margin-top: 12px;
          font-size: 36px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 600;
          color: #9e5014;

          span {
            &:first-child {
              font-size: 24px;
            }
          }
        }

        &-active {
          border-color: #f1423d;
          background: #fff2f2;
        }
      }
    }

    .type-row {
      display: flex;
      padding-top: 63px;
      display: flex;
      justify-content: center;

      .pay-type {
        display: flex;

        .card {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          margin-right: 38px;

          .icon {
            width: 116px;
            height: 116px;
            border: 1px solid #93d375;
            display: flex;
            align-items: center;
            justify-content: center;

            img {
              width: 100px;
              height: 100px;
            }
          }

          .names {
            margin-top: 16px;
            display: flex;
            align-items: center;

            img {
              display: block;
              width: 17px;
              height: 15px;
            }

            span {
              margin-left: 5px;
              font-size: 14px;
              font-family: PingFang SC, PingFang SC;
              font-weight: 400;
              color: #666666;
            }
          }

          &:last-child {
            .icon {
              border-color: #05b6fc;
            }

            .names {
              img {
                width: 18px;
                height: 18px;
              }
            }
          }
        }
      }

      .price-info {
        .price {
          font-size: 36px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 600;
          color: #fa6500;

          span {
            &:first-child {
              font-size: 24px;
            }
          }
        }

        .old-price {
          margin-left: 8px;
          font-size: 16px;
          font-family: HONOR Sans, HONOR Sans;
          font-weight: 400;
          color: #999999;
          position: relative;
          bottom: 10px;
          text-decoration: line-through;
        }

        .select {
          width: 262px;
          margin-top: 8px;
        }

        .tips {
          margin-top: 10px;
          font-size: 12px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;

          span {
            color: #666;

            &:last-child {
              cursor: pointer;
              color: #f1423d;
            }
          }
        }
      }
    }
  }
}
</style>
